package com.sss.myspringsecurity.web.controller;


import com.sss.myspringsecurity.web.service.ISssUserService;
import com.sss.myspringsecurity.util.JwtUtil;
import com.sss.myspringsecurity.util.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author sss
 * @since 2020-02-09
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class SssUserController {

    private final ISssUserService sssUserService;
    @Resource
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public Result login(String userName,String password){
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userName, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException)
            {
                throw new BadCredentialsException("用户不存在或密码错误!!!");
            }
        }
        String token = JwtUtil.createToken(userName);
//        Object principal = authentication.getPrincipal();
//        System.out.println(principal);
        return Result.succes(token);
    }

    @GetMapping("/menus")
   // @PreAuthorize("hasAuthority('aaann')")
    public Result test(){
        return Result.succes("spring-security配置成功");
    }

}

